﻿// <copyright file="SearchExtensionMethods.cs" company="Snowman Consulting">
//     Copyright (c) 2009 Snowman Consulting. All rights reserved.
// </copyright>

namespace SnowmanConsulting.ProductKeyManager.Search
{
    using System;
    using System.Globalization;

    /// <summary>
    /// Extension methods for searching
    /// </summary>
    public static class SearchExtensionMethods
    {
        /// <summary>
        /// Calculates the similarity.
        /// </summary>
        /// <param name="search">The search.</param>
        /// <param name="source">The source.</param>
        /// <param name="result">The result.</param>
        public static void CalculateSimilarity(this string search, string source, ref decimal result)
        {
            result = search.CalculateSimilarity(source);
        }

        /// <summary>
        /// Calculates the similarity.
        /// </summary>
        /// <param name="search">The search.</param>
        /// <param name="source">The source.</param>
        /// <returns>The result</returns>
        public static decimal CalculateSimilarity(this string search, string source)
        {
            if (source.Length >= 0)
            {
                if (search.Equals(source))
                {
                    return 1m;
                }

                decimal similarlen = 0m;

                string[] words = search.Split(' ');
                foreach (string word in words)
                {
                    if (source.Contains(word))
                    {
                        similarlen += word.Length;
                    }
                }

                return similarlen / source.Length;
            }

            return 0m;
        }

        /// <summary>
        /// Determines whether the specified source contains keywords.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="value">The keyword string.</param>
        /// <returns>
        /// <c>true</c> if the specified source contains keywords; otherwise, <c>false</c>.
        /// </returns>
        public static bool ContainsKeywords(this string source, string value)
        {
            string[] keywords = value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            bool match = false;

            foreach (string keyword in keywords)
            {
                if (source.ToLower(CultureInfo.CurrentCulture).Contains(keyword))
                {
                    match = true;
                }
                else
                {
                    return false;
                }
            }

            return match;
        }
    }
}
